<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <style>
      /* div {
        width: 200px;
        height: 200px;
        border: 1px solid #30897c;
      } */
    </style>
    <title>聊天室</title>
  </head>
  <body>
    <input type="text" placeholder="输入你的内容" name="" id="" />
    <button>发送请求</button>
    <!-- 显示结果 -->
    <div></div>
  </body>
</html>

<script>
  var input = document.querySelector("input");
  var button = document.querySelector("button");
  var div = document.querySelector("div");
  const TYPE_ENTER = 0;
  const TYPE_LEAVE = 1;
  const TYPE_MSG = 2;
  // 演示websocket在浏览器端如何使用
  // H5已经直接提供了websocket的API，所以我们可以直接使用

  // 1.创建websocket
  // 参数1:websocket的服务器地址

  var socket = new WebSocket("ws://localhost:3000"); //看02里面端口号是多少

  // open：当和websocket服务器连接成功的时候触发
  socket.addEventListener("open", function () {
    div.innerHTML = "连接服务成功了！";
  });

  // 3，主动给websocket服务发送消息
  button.addEventListener("click", () => {
    var value = input.value;
    socket.send(value);
    input.value = "";
  });

  // 4.接受websocket服务的数据
  socket.addEventListener("message", (e) => {
    var data = JSON.parse(e.data);
    console.log(data);
    var dv = document.createElement("div");
    dv.innerHTML = data.msg + "--->" + data.time;
    if (data.type === TYPE_ENTER) {
      dv.style.color = "green";
    } else if (data.type === TYPE_LEAVE) {
      dv.style.color = "red";
    } else {
      dv.style.color = "blue";
    }
    div.appendChild(dv);
  });

  socket.addEventListener("close", () => {
    console.log("服务器断开。。。");
  });
</script>
